package com.example.banksys;

import DataBase.myDB;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AddTradeItemController {
    public TextField name;
    public ComboBox<String> type;
    public TextArea description;
    public ComboBox<String> duration;
    public Button clear;
    public Button submit;
    public AnchorPane pane;
    public TextField rate;
    public Label labelll;

    private double ratio;

    public void initialize() throws SQLException {
        ratio=0;
        rate.setEditable(false);
        type.getItems().add("save");
        type.getItems().add("take");
        type.getItems().add("loan");
        type.getItems().add("financialProduct");
        myDB database=new myDB("banksystem");
        String sql="select distinct duration from trade_type";
        ResultSet res=database.getStatement().executeQuery(sql);
        while(res.next()){
            duration.getItems().add(res.getString(1));
        }
        duration.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                if(!duration.getValue().equals("instant")){
                    rate.setEditable(true);
                }else{
                    rate.setEditable(false);
                    rate.setText("");
                    ratio=0;
                }
            }
        });
    }


    public void add() throws SQLException {
        if(name.getText().isEmpty()||name.getText()==null||type.getValue()==null||description.getText().isEmpty()||description.getText()==null||duration.getValue()==null||(!duration.getValue().equals("instant")&&(rate.getText().isEmpty()||rate.getText().equals("")))){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.titleProperty().set("错误");
            alert.headerTextProperty().set("请完善所有信息！");
            alert.showAndWait();
        }else{
            if(!duration.getValue().equals("instant"))
                ratio=Double.parseDouble(rate.getText());
            myDB database=new myDB("banksystem");
            String sql="insert into trade_type values ('"+duration.getValue()+"','"+type.getValue()+"',null,'"+name.getText()+"','"+description.getText()+"',"+ratio+")";
            database.getStatement().execute(sql);
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.titleProperty().set("信息");
            alert.headerTextProperty().set("操作成功！");
            alert.showAndWait();
            ManageTradeManageController.needRefresh.set(true);
            pane.getScene().getWindow().hide();

        }
    }

}
